import { ref, reactive } from "vue";
import _ from "lodash";

export default (requestFn, config) => {
  const isLoading = ref(false);
  const listData = ref([]);
  const listTotal = ref(0);
  const pageParams = reactive({
    current: 1,
    size: 20,
    ...config
  });

  const getListData = async () => {
    try {
      isLoading.value = true;
      const params = {
        ...pageParams,
        size: pageParams.size === "-1" ? listTotal.value : pageParams.size
      };
      const {
        data: { list = [], total = 0 }
      } = await requestFn(params);
      isLoading.value = false;
      listData.value = list;
      listTotal.value = total;
    } catch (err) {
      console.log("listHook>>>", err);
      isLoading.value = false;
    }
  };

  const handelPage = _.debounce(val => {
    pageParams.size = val.limit;
    pageParams.current = val.page;
    getListData();
  }, 500);
  const handelPageSize = _.debounce(val => {
    pageParams.size = val;
    getListData();
  }, 500);

  const handelSearch = _.debounce(() => {
    pageParams.current = 1;
    listData.value.length = 0;
    getListData();
  }, 500);

  getListData();
  return {
    isLoading,
    listData,
    listTotal,
    pageParams,
    getListData,
    handelPage,
    handelPageSize,
    handelSearch
  };
};
